package com.dream.inflammable;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.wzsdk.attention.Equipment;
import com.example.wzsdk.login.Landing;
import com.example.wzsdk.login.LoginState;
import com.example.wzsdk.scan.Search;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

public class MainActivity extends Activity implements View.OnClickListener, Search.SearchFish, AdapterView.OnItemClickListener, LoginState {

    //IP地址
    private TextView ipAdress;
    //设备值
    private TextView value;
    //登录按钮，搜索按钮，连接按钮，关闭按钮
    private Button loginbtn,scanbtn,connbtn,closebtn;
    //搜索IP地址弹出框
    private ProgressDialog progressDialog;
    private AlertDialog.Builder builder;
    private AlertDialog alertDialog;
    private List<String> ipList;
    //本地存储类
    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor editor;
    //搜索类
    private Search search;
    //登录类
    private Landing landing;
    //Hanlder消息
    private Message message;
    //变量ID
    private int VariableID;
    //设备ID
    private int DeviceID;
    //UIID
    private String UIID;

    private static final int SEARCH=0;
    private static final int BTN_ON=1;
    private static final int ERROR=2;
    private static final int SET_VAL=3;

    //当前设备
    private static final String DEVICE_NAME="光敏";

    //Handler消息
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(final Message msg) {
            switch (msg.what){
                case SEARCH:
                    ListView listView=new ListView(MainActivity.this);
                    listView.setAdapter(new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,ipList));
                    listView.setOnItemClickListener(MainActivity.this);
                    builder.setView(listView);
                    alertDialog=builder.show();
                    break;
                case BTN_ON:
                    connbtn.setEnabled(true);
                    closebtn.setEnabled(true);
                    break;
                case ERROR:
                    Toast.makeText(MainActivity.this,msg.obj.toString(),Toast.LENGTH_SHORT).show();
                    break;
                case SET_VAL:
                    value.setText(DEVICE_NAME+"："+msg.obj.toString());
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    //初始化控件
    public void initView(){
        sharedPreferences=getSharedPreferences("appinfo",MODE_PRIVATE);
        editor=sharedPreferences.edit();

        //首次启动生成APPID
        if (!sharedPreferences.getBoolean("isFirst",false)) getAPPID();

        ipAdress = (TextView) findViewById(R.id.ipAdress);
        value = (TextView) findViewById(R.id.value);
        scanbtn= (Button) findViewById(R.id.scan);
        loginbtn= (Button) findViewById(R.id.login);
        connbtn= (Button) findViewById(R.id.conn);
        closebtn= (Button) findViewById(R.id.close);
        search = new Search(sharedPreferences.getString("appid","default"));
        landing = new Landing(sharedPreferences.getString("appid","default"));
        landing.setLoginState(this);
        progressDialog=new ProgressDialog(this);
        progressDialog.setMessage("搜索中...");
        builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("IP列表");
    }

    //首次运行执行，得到APPID并保存到本地
    public void getAPPID() {
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 8; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        editor.putString("appid",sb.toString());
        editor.putBoolean("isFirst",true);
        editor.commit();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            //搜索
            case R.id.scan:
                progressDialog.show();
                search.EngSearch(this);
                search.setSearchFish(this);
                break;
            //登录
            case R.id.login:
                landing.Login(ipAdress.getText().toString(),5800);
                break;
            //关注
            case R.id.conn:
                List<String[]> dateList = new Equipment().getDateList();
                if (dateList!=null&&dateList.size()>0){
                    for (int i = 0; i < dateList.size(); i++) {
                        System.out.println(Arrays.toString(dateList.get(i)));
                        if (dateList.get(i)[0].contains(DEVICE_NAME)){
                            //关注变量
                            VariableID=Integer.parseInt(dateList.get(i)[3].substring(5));
                            landing.atnVariable(VariableID);
                        }
                    }
                }else {
                    senError("未检测到设备");
                }
                break;
            //断开
            case R.id.close:
                //取消关注变量
                if (VariableID!=0){
                    landing.canVariable(VariableID);
                }
                break;
        }
    }

    //开始连接时
    @Override
    public void AttentionStarting(String s, byte b, boolean b1) {
        //关注变量值
        if (b1){
            senMessge(b+"");
        }
    }

    //状态改变时
    @Override
    public void AttentionProcess(String s, byte b, String s1) {
        //关注变量值
        senMessge(b+"");
    }

    //设备状态改变时
    @Override
    public void SetVarState(String s, byte b) {

    }

    //退出登录
    @Override
    protected void onDestroy() {
        if (landing!=null){
            landing.exitLogin();
        }
        super.onDestroy();
    }

    //IP列表点击事件
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        alertDialog.dismiss();
        loginbtn.setEnabled(true);
        ipAdress.setText(ipList.get(position));
    }

    //登录结果
    @Override
    public void LoginStatus(boolean b) {
        if (b){
            handler.sendEmptyMessage(BTN_ON);
        }else {
            senError("已退出登录");
            return;
        }
    }

    //发送错误消息
    public void senError(String error){
        message=new Message();
        message.what=ERROR;
        message.obj=error;
        handler.sendMessage(message);
    }

    //发送消息
    public void senMessge(String val){
        message=new Message();
        message.what=SET_VAL;
        message.obj=val;
        handler.sendMessage(message);
    }

    //搜索完成时回调Wifi接口
    @Override
    public void SearchFishWifi(List<String[]> list) {

    }
    //搜索完成时回调万纳接口
    @Override
    public void SearchFishWna(List<String[]> list) {
        progressDialog.dismiss();
        if (list==null||list.size()==0){
            senError("未搜索到主机");
            return;
        }
        ipList=new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            ipList.add(list.get(i)[0]);
        }
        handler.sendEmptyMessage(SEARCH);
    }
}
